<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header @addTodo="addTodo" />
      <List :state="todos" />
      <Footer v-model:todos="todos" />
    </div>
  </div>
</template>

<script lang="ts">
import { Todo } from './types/todo'
import { readTodos, saveTodos } from './utils/localStoregeUtils'
import { defineComponent, reactive, toRefs, provide, watch } from 'vue'
import Footer from 'components/Footer.vue'
import Header from 'components/Header.vue'
import List from 'components/List.vue'

export default defineComponent({
  components: { Header, List, Footer },
  name: 'App',
  setup() {
    // 数据应该用数组来存储，数组中的每个数据都是一个对象,对象中应该有三个属性(id,title,isCompleted)
    // 把数据暂且定义了App.vue父级组件
    // 定义一个数组数据
    const state = reactive<{ todos: Todo[] }>({
      todos: readTodos()
    })
    const addTodo = (todo: Todo) => {
      state.todos.unshift(todo)
    }

    const deleteTodo = (id: number) => {
      let currentIndex: number = state.todos.findIndex(item => item.id === id)
      state.todos.splice(currentIndex, 1)
    }
    const changeState = (id: number, value: boolean) => {
      const findTodo: Todo | undefined = state.todos.find(
        item => item.id === id
      )
      if (findTodo) {
        findTodo.isCompleted = value
      }
    }

    provide('deleteTodo', deleteTodo)
    provide('changeState', changeState)
    watch(state, (newValue: any) => {
      saveTodos(newValue)
    })
    return { ...toRefs(state), addTodo, deleteTodo }
  }
})
</script>

<style scoped>
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>